package org.example.user.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.example.comment.utils.ThreadLocalUtil;
import org.example.constant.MessageConstant;
import org.example.entity.User;
import org.example.user.exception.UserNotExistException;
import org.example.user.mapper.UserMapper;
import org.example.user.service.UserService;
import org.example.vo.LoginVo;
import org.example.vo.UserInfoVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author fanfutian
 * @since 2025-04-24
 */
@Slf4j
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public LoginVo login(String username, String password) {
        User user = userMapper.selectUserByUsername(username);

        if (user == null){
            throw new UserNotExistException(MessageConstant.USER_NOT_FOUND);
        }
        if (!user.getPassword().equals(password)){
            throw new UserNotExistException(MessageConstant.PASSWORD_ERROR);
        }

        if(!user.getStatus().equals(1)){
            throw new UserNotExistException(MessageConstant.USER_LOCK);
        }

        log.info("user:"+ user.toString());
        LoginVo loginVo = new LoginVo();
        BeanUtils.copyProperties(user,loginVo);
        return loginVo;
    }

    @Override
    public UserInfoVo getUserInfo() {
        Long userId = ThreadLocalUtil.get();
        User user = userMapper.selectById(userId);
        UserInfoVo userInfoVo = new UserInfoVo();
        BeanUtils.copyProperties(user,userInfoVo);
        return userInfoVo;
    }


    @Transactional
    @Override
    public void updateUserInfo(UserInfoVo userInfoVo) {
        Long userId = ThreadLocalUtil.get();
        User user = new User();
        user.setId(userId);
        user.setUpdateTime(LocalDateTime.now());
        BeanUtils.copyProperties(userInfoVo,user);
        userMapper.updateById(user);
    }


    @Transactional
    @Override
    public void updateUserPhone(String phone) {
        Long userId = ThreadLocalUtil.get();
        User user = new User();
        user.setId(userId);
        user.setUpdateTime(LocalDateTime.now());
        user.setPhone(phone);
        userMapper.updateById(user);
    }
}
